import 'package:enjoy_plus_hm/utils/http.dart';
import 'package:enjoy_plus_hm/utils/toast.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  // 地址
  String currentAddress = '暂无地址';
  // 高德地图API
  final String baseUrl = 'https://restapi.amap.com/v3';
  // 高德地图API密钥
  final String apiKey = 'ec6f580a9ed57f6731978c15a3a50fb1';
// 附近小区
  List nearbyCommunities = [];

  @override
  void initState() {
    super.initState();
    // 1.检测是否配置位置授权
    requestLocationPermission();
    // 获取当前位置的信息
    reverseGeocoding(40.065956, 116.350077);
    // 获取附近小区
    queryNearbyCommunities(40.065956, 116.350077);
  }

  // 1.检测是否配置位置授权
  requestLocationPermission() async {
    PermissionStatus status = await Permission.location.request();
    if (status.isGranted) {
      // 权限授予
      ToastUtil.showSuccess('位置权限授予');
      // 2.使用Geolocator获取当前位置的经纬度
      getCurrentLocation();
      // 3.使用逆地址解析获取当前位置的详细地址
      reverseGeocoding(40.065956, 116.350077);
    } else {
      // 权限未授予
      ToastUtil.showError('位置权限未授予, 请去设置中心开启');
    }
  }

  //使用Geolocator获取当前位置的经纬度
  getCurrentLocation() async {
    /// 位置设置变量，用于存储位置相关的配置信息
    /// 类型为LocationSettings，通常包含位置服务的相关配置参数
    late LocationSettings locationSettings;

    if (defaultTargetPlatform == TargetPlatform.android) {
      // 针对Android平台，设置高精度定位、100米距离过滤、强制使用位置管理器等
      locationSettings = AndroidSettings(
          accuracy: LocationAccuracy.high,
          distanceFilter: 100,
          forceLocationManager: true,
          intervalDuration: const Duration(seconds: 10),
          foregroundNotificationConfig: const ForegroundNotificationConfig(
            notificationText:
                "Example app will continue to receive your location even when you aren't using it",
            notificationTitle: "Running in Background",
            enableWakeLock: true,
          ));
    } else if (defaultTargetPlatform == TargetPlatform.iOS ||
        defaultTargetPlatform == TargetPlatform.macOS) {
      // 针对iOS和macOS平台，设置高精度定位、健身活动类型、100米距离过滤等
      locationSettings = AppleSettings(
        accuracy: LocationAccuracy.high,
        activityType: ActivityType.fitness,
        distanceFilter: 100,
        pauseLocationUpdatesAutomatically: true,
        // 只有在应用在后台启动时才设置为true
        showBackgroundLocationIndicator: false,
      );
    } else if (kIsWeb) {
      // 针对Web环境，设置高精度定位、100米距离过滤、5分钟的最大年龄等
      locationSettings = WebSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
        maximumAge: const Duration(minutes: 5),
      );
    } else {
      // 对于其他平台，默认设置高精度定位和100米距离过滤
      locationSettings = const LocationSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
      );
    }

    try {
      // 使用配置好的定位设置获取当前位置
      Position position = await Geolocator.getCurrentPosition(
          locationSettings: locationSettings);
      // 显示成功获取到的纬度和经度
      ToastUtil.showSuccess('${position.latitude}, ${position.longitude}');
      //todo: 使用经纬度进行定位
    } catch (e) {
      ToastUtil.showError('获取位置失败');
      // 处理可能出现的异常
      print(e.toString());
    }
  }

// 逆地址解析 高德地图
  Future<void> reverseGeocoding(double latitude, double longitude) async {
    String url =
        '$baseUrl/geocode/regeo?key=$apiKey&location=$longitude,$latitude';
    try {
      var response = await MyHttp.get(url);
      print(response['regeocode']['formatted_address']);
      setState(() {
        currentAddress = response['regeocode']['formatted_address'];
      });
    } catch (e) {
      print('查询过程中出现错误: $e');
    }
  }

//获取周边小区
  Future<void> queryNearbyCommunities(double latitude, double longitude) async {
    String url =
        '$baseUrl/place/around?key=$apiKey&location=$longitude,$latitude&radius=500&types=住宅小区';
    try {
      var response = await MyHttp.get(url);
      for (var element in (response['pois'] as List)) {
        print(element['name']);
        setState(() {
          nearbyCommunities.add(element);
        });
      }
    } catch (e) {
      ToastUtil.showError('查询周边小区失败');
      print('查询过程中出现错误: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('选择社区'),
        ),
        body: ListView(
          padding: const EdgeInsets.all(10),
          children: [
            const Row(
              children: [
                Text(
                  '当前地址',
                  style: TextStyle(color: Colors.grey),
                )
              ],
            ),
            const SizedBox(height: 10),
            Container(
              color: Colors.white,
              padding: const EdgeInsets.all(10),
              child: Row(
                children: [
                  Expanded(child: Text(currentAddress)),
                  GestureDetector(
                      onTap: () {
                        // 使用经纬度进行逆地址解析
                        reverseGeocoding(40.065956, 116.350077);
                      },
                      child: Row(
                        children: [
                          Icon(Icons.location_searching_outlined,
                              color: Colors.blue),
                          SizedBox(width: 2),
                          Text(
                            '重新定位',
                            style: TextStyle(color: Colors.blue),
                          ),
                        ],
                      ))
                ],
              ),
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '附近社区',
                  style: TextStyle(color: Colors.grey),
                )
              ],
            ),
            const SizedBox(height: 10),
            ListView(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                children: nearbyCommunities
                    .map((item) => GestureDetector(
                          onTap: () {
                            Navigator.pushNamed(context, '/building_list',
                                arguments: {'point': item['name']});
                          },
                          child: Container(
                              color: Colors.white,
                              padding: const EdgeInsets.all(10),
                              child: Row(children: [
                                Expanded(child: Text('${item['name']}')),
                                const Row(children: [
                                  Icon(Icons.arrow_forward_ios,
                                      size: 16, color: Colors.black),
                                ])
                              ])),
                        ))
                    .toList()),
          ],
        ));
  }
}
